package exabase.localClientProxy;

import java.io.IOException;
import java.net.Socket;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;

import exabase.com.dataTransfer.DataTransfer;
import exabase.data.Data;
import exabase.data.Hash;
import exabase.meta.Meta;

public class LocalClientProxy {
	private static Logger logger = Logger.getLogger(LocalClientProxy.class
			.getName());

	protected static LocalClientProxy instance;

	protected Set<Meta> metas;
	protected Set<Data> datas;
	protected String host = "localhost";

	protected DataTransfer dataTransfer;

	protected LocalClientProxy() {
	}

	public static LocalClientProxy getInstance() {
		if (instance == null)
			instance = new LocalClientProxy();
		return instance;
	}

	protected DataTransfer getDataTransfer() throws Exception {
		if (dataTransfer == null) {
			Socket socket = new Socket(host, 8386);
			dataTransfer = new DataTransfer(socket);

			logger.fine("Connect: " + socket.toString());
		}
		return dataTransfer;
	}

	public Hash add(String dataFileName, String metaFileName)
			throws IOException, Exception {
		Hash hash = getDataTransfer().sendDataWithAck(dataFileName);
		Meta meta = new Meta(metaFileName, hash);
		getDataTransfer().sendMeta(meta);
		return hash;
	}

	public Set<Meta> getAllMeta() throws IOException, ClassNotFoundException,
			Exception {
		metas = getDataTransfer().getAllMeta();
		return metas;
	}

	public Set<Data> getDataSet() {
		if (datas == null)
			datas = new TreeSet<Data>();
		return datas;
	}

	public void getData(Hash hash) throws IOException, ClassNotFoundException,
			Exception {
		Data data = getDataTransfer().getData(hash);
		if (data != null)
			getDataSet().add(data);
	}

	public void updateMeta(Hash hash, String metaFileName) throws IOException,
			Exception {
		Meta meta = new Meta(metaFileName, hash);
		getDataTransfer().sendMeta(meta);
	}

	public void disconnect() throws IOException, Exception {
		if (dataTransfer != null) {
			logger.fine("Disconnect: " + dataTransfer.getSocket().toString());
			dataTransfer.disconnect();
			dataTransfer = null;
		}
	}
}
